package day_2022_9_to_12.Day;

import java.util.Arrays;
import java.util.Collections;

/**
 * @author haomin
 * @date 2022/09/13 09:06
 **/
public class Day11_1_Num670_MaximumSwap {
    public static void main(String[] args) {
        int num = 123;
        char[] arr = String.valueOf(num).toCharArray();
        System.out.println(arr);
    }
    public static int maximumSwap(int num) {
        String s = String.valueOf(num);
        if(s.length() <= 1) return num;
        Integer[] arr = new Integer[s.length()];
        Integer[] brr = new Integer[s.length()];
        for (int i = 0; i < s.length(); i++) {
            arr[i] = s.charAt(i) - '0';
            brr[i] = arr[i];
        }
        // java并没有直接提供数组逆序的api，因此借助工具类，此时数组要为Integer类型
        Arrays.sort(brr, Collections.reverseOrder());
        for (int i = 0; i < arr.length; i++) {
            if (!arr[i].equals(brr[i]) ) {
                for (int j = arr.length - 1; j >= 0; j--) {
                    if (arr[j].equals(brr[i])) {
                        int temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                        break;
                    }
                }
                break;
            }
        }

        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < arr.length; k++) {
            sb.append(String.valueOf(arr[k]));
        }
        return Integer.valueOf(sb.toString());
    }
    class Solution {
        public int maximumSwap(int num) {
            char[] arr = String.valueOf(num).toCharArray();
            for(int i = 0; i < arr.length; ++i){
                int index = i;
                for(int j = arr.length-1; j > i; --j){
                    if(arr[index] < arr[j]) index = j;
                }
                if(index != i){
                    char temp = arr[i];
                    arr[i] = arr[index];
                    arr[index] = temp;
                    return Integer.parseInt(new String(arr));
                }
            }
            return num;
        }
    }
}